/**
 * 实现功能如下：
 * 1. 按帧读取视频mp4文件
 * 读取出来的视频为yuv格式，音频为pcm(float32)格式
 *
 * 注意事项：
 * 1. 读取出来的数据最后都会有一些无效数据，需要手工清除掉
 */

const beamcoder = require('beamcoder');
async function run() {
    let demuxer = await beamcoder.demuxer('../../media/gh_1.mp4');
    let videoDecoder = beamcoder.decoder({params:demuxer.streams[0].codecpar});
    let audioDecoder = beamcoder.decoder({params:demuxer.streams[1].codecpar});

    let audioCount = 0, videoCount = 0;
    let packet = {};
    for ( let x = 0 ; x < 100 && packet != null ; x++ ) {
        packet = await demuxer.read(); // Read next frame. Note: returns null for EOF
        if (packet) {
            if (packet.stream_index === 0) {
                let frames = await videoDecoder.decode(packet);
                console.log(x, `收到视频帧，frameLength:${frames.frames.length}, total_time:${frames.total_time}`);
                videoCount++;
            }else if(packet.stream_index === 1){
                let audioFrames = await audioDecoder.decode(packet);
                console.log(x, `>>>>收到音频帧，frameLength:${audioFrames.frames.length}, total_time:${audioFrames.total_time}`);
                audioCount++;
            }
        }
    }
    console.log(`===================================`);
    console.log(`videoCount:${videoCount}, audioCount:${audioCount}`);

    let frames = await videoDecoder.flush(); // Must tell the videoDecoder when we are done
    console.log('flush', frames.total_time, frames.length);
}

run();